﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.UI;
using SingleUserMall.Common;
using SingleUserMall.Dividends.Form;
using SingleUserMall.Dividends.VO;

namespace SingleUserMall.Dividends
{
    public class DividendManageAppService : SingleUserMallAppServiceBase, IDividendManageAppService
    {
        private readonly IRepository<Dividend, long> _dividendRepository;
        public DividendManageAppService(IRepository<Dividend, long> dividendRepository)
        {

            _dividendRepository = dividendRepository;
        }

        public async Task<PagedResultDto<DividendVO>> GetDividendsAsync(PagedForm form)
        {
            var query = _dividendRepository.GetAll().OrderByDescending(x => x.CreationTime);
            return await query.ToPagedResultDtoAsync<Dividend, DividendVO>(form, (i, vo) =>
            {
                vo.DividendAmountView = ((int)(i.DividendAmount * 100)).ToString();
            });
        }
        public async Task SaveDividendsAsync(DividendForm form)
        {
            try
            {
                var dividend = await _dividendRepository.FirstOrDefaultAsync(x => x.Id == form.Id);
                if (dividend != null)
                {
                    dividend = form.MapTo(dividend);
                    await _dividendRepository.UpdateAsync(dividend);
                }
                else
                {
                    dividend = form.MapTo<Dividend>();
                    await _dividendRepository.InsertAsync(dividend);

                }
                await CurrentUnitOfWork.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }
        public async Task DeleteDividendsAsync(SingleId<long> form)
        {
            await _dividendRepository.DeleteAsync(x => x.Id == form.Id);
        }

    }
}
